#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>  // topper
#include <string.h> // bzero
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>  // sockaddr_in
#include <unistd.h> // fork
#define PORT 8888
#define BACKLOG 20
void process_conn_server(int s);
int main(int argc, char * argv[])
{

    int serverSocket, clientSocket;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    int err;    // 返回值
    pid_t pid;
    // 建立套结字
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0)
    {
        printf("create socket failed.\n");
        return -1;
    }
    else
    {
        printf("create socket successed\n");
    }
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    err = bind(serverSocket, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if (err < 0)
    {
        printf("bind error\n");
        return -1;
    }
    else
    {
        printf("bind successed\n");
    }
    err = listen(serverSocket, BACKLOG);
    if (err < 0)
    {
        printf("listen failed\n");
        return -1;
    }
    else
    {
        printf("listen successed\n");
    }
    // for (int i = 0; i < 2; ++i)
    while (1)
    {
        socklen_t addrlen = sizeof(struct sockaddr);
        clientSocket = accept(serverSocket, (struct sockaddr*)&server_addr, &addrlen);
        if (clientSocket < 0)
        {
            printf("accept failed\n");
            continue;
        }
        else
        {
            printf("accept successed\n");
            printf("client ip: %s\n", inet_ntoa(server_addr.sin_addr));
            printf("client port: %d\n", ntohs(server_addr.sin_port));
        }
        
        pid = fork();
        if (pid == 0)
        {
            close(serverSocket);
            process_conn_server(clientSocket);
            // return 0;
            exit(0);
        }
        else
        {
            close(clientSocket);
        }
    }
    close(serverSocket);
    
    // char buffer[BUFSIZ];
    // while (1)
    // {
        
    //     int ret = read(clientSocket, buffer, sizeof(buffer));
    //     write(STDOUT_FILENO, buffer, ret);

    //     for (int i = 0; i < ret; ++i)
    //     {
    //         buffer[i] = toupper(buffer[i]);
    //     }
    //     write(clientSocket, buffer, ret);
    // }

    return 0;
}
void process_conn_server(int clientfd)
{
    ssize_t size = 0;
    char buffer[1024];
    while (1)
    {
        size = read(clientfd, buffer, 1024);
        // if (size == 0)
        // {
        //     return;
        // }
        if (buffer[0] == 'q')
            break;
        sprintf(buffer, "%d bytes altogether\n", size);
        write(clientfd, buffer, strlen(buffer) + 1);
    }
    close(clientfd);
;}